package client

import (
	"context"
	"gitee.com/byx_darwin/geo-rpc/kitex_gen/geo/service"
	clientConf "gitee.com/byx_darwin/micro-extend/pkg/config/client"
	"gitee.com/byx_darwin/micro-extend/pkg/options/rpc"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	"github.com/cloudwego/kitex/client"
	kClient "github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/pkg/remote/codec/thrift"
	"github.com/cloudwego/kitex/pkg/rpcinfo"
	"github.com/cloudwego/kitex/pkg/transmeta"
	"github.com/cloudwego/kitex/transport"
	"github.com/kitex-contrib/polaris"
	"time"
)

func NewRPCClientWithPolaris(ctx context.Context,
	confClient clientConf.Client, polaris clientConf.Polaris, jaeger clientConf.Jaeger,
	clientName, serverName string, suite *polaris.ClientSuite,
	log hlog.CtxLogger) (service.Client, error) {
	opts, err := rpc.ClientOptions(confClient, polaris, jaeger, clientName, suite, log)
	if err != nil {
		log.CtxErrorf(ctx, "create node rpc client failure,err:%v", err)
		return nil, err
	}
	rpcClient, err := service.NewClient(serverName, opts...)
	if err != nil {
		log.CtxErrorf(ctx, "%s 客户端连接失败 err：%s", serverName, err)
		return nil, err
	}
	log.CtxDebugf(ctx, "%s 客户端连接成功 ", serverName)
	return rpcClient, nil
}

func NewRPCClient(ctx context.Context,
	conf clientConf.RpcClientConf, log hlog.CtxLogger) (service.Client, error) {
	opts := make([]client.Option, 0, 7)
	opts = append(opts, client.WithHostPorts(conf.Addr))                                                       // 设置RPC客户端的地址
	opts = append(opts, client.WithMuxConnection(conf.MuxConnectionNum))                                       // 设置RPC客户端的Mux连接数
	opts = append(opts, client.WithRPCTimeout(conf.RpcTimeout*time.Second))                                    // 设置RPC客户端的超时时间
	opts = append(opts, client.WithClientBasicInfo(&rpcinfo.EndpointBasicInfo{ServiceName: conf.ServiceName})) // 设置RPC客户端的基本信息
	opts = append(opts, client.WithMetaHandler(transmeta.ClientTTHeaderHandler))
	code := thrift.NewThriftCodec()
	opts = append(opts, kClient.WithPayloadCodec(code))
	framed := kClient.WithTransportProtocol(transport.TTHeaderFramed)
	opts = append(opts, framed)

	rpcClient, err := service.NewClient(conf.ServiceName, opts...)
	if err != nil {
		log.CtxErrorf(ctx, "%s 客户端连接失败 err：%s", conf.ServiceName, err)
		return nil, err
	}
	log.CtxDebugf(ctx, "%s 客户端连接成功 ", conf.ServiceName)
	return rpcClient, nil
}
